#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "db_access.h"
#include "debug.h"
#include "unidev.h"
#include "utils.h"

int running = 1;
struct sqlite3db db;

static void signalhandler(int signo)
{
    running = 0;
}


static void attr_cb(const cJSON *result)
{
    char *content;

    content = cJSON_Print(result);
    LOGD("%s", content);
    cJSON_free(content);
}


static void join_cb(const cJSON *result)
{
    char *content;

    content = cJSON_Print(result);
    LOGD("%s", content);
    cJSON_free(content);
}

static void quit_cb(const cJSON *result)
{
    char *content;

    content = cJSON_Print(result);
    LOGD("%s", content);
    cJSON_free(content);
}

static cJSON *json_retrieve(char *filename)
{
    char *filebuf;
    size_t filesize;
    cJSON *root = NULL;

    filebuf = utils_fileread(filename, NULL, &filesize);
    if (NULL == filebuf)
    {
        LOGE("read file %s error", filename);
        return NULL;
    }
    root = cJSON_ParseWithLength(filebuf, filesize);
    if (NULL == root)
    {
        LOGE("parse file %s error", filename);
        free(filebuf);
        return NULL;
    }

    free(filebuf);
    return root;
}

int main(int argc, char **argv)
{
    int ret = 0;
    cJSON *root, *cnf = NULL, *attr_map = NULL;
    cJSON *request, *pdu;
    char result[512];

    request = cJSON_CreateObject();
    cJSON_AddNumberToObject(request, "ret", -1);
    pdu = cJSON_AddObjectToObject(request, "pdu");
    cJSON_AddStringToObject(pdu, "uuid", "xxx");
    cJSON_AddNumberToObject(pdu, "attr id", 0);
    cJSON_AddNumberToObject(pdu, "operation", 0);
    cJSON_AddNumberToObject(pdu, "channel", 0);
    cJSON_AddStringToObject(pdu, "value", "2");

    signal(SIGINT, signalhandler);

    db_init(&db);


    root = cJSON_CreateObject();

    cnf = cJSON_CreateObject();
    cJSON_AddStringToObject(cnf, "interface", "/dev/ttyUSB0");
    cJSON_AddNumberToObject(cnf, "baud", 115200);
    cJSON_AddItemToObject(root, "cnf", cnf);

    attr_map = json_retrieve("./zm32.json");
    cJSON_AddItemToObject(root, "attr map", attr_map);

    ret = init(attr_cb, join_cb, quit_cb, root);
    if (ret != UNIDEV_SUCCESS)
    {
        LOGE("init error");
        goto out;
    }
    while (running) {
        ret = rdwr_sync(request, result);
        sleep(5);
    }

    sleep(2);

    ret = finit();

out:
    db_deinit(&db);
    cJSON_Delete(root);
    root = NULL;
    return ret;
}